import { Client } from 'minio';

const minioClient = new Client({
  endPoint: process.env.MINIO_ENDPOINT?.replace('http://', '') || '175.178.120.172',
  port: Number(process.env.MINIO_PORT || 9000),
  useSSL: false,
  accessKey: process.env.MINIO_ACCESS_KEY || 'minioadmin',
  secretKey: process.env.MINIO_SECRET_KEY || '!Aa8826701'
});

const bucketName = process.env.MINIO_BUCKET_NAME || 'kason-world';

async function ensureBucket() {
  const exists = await minioClient.bucketExists(bucketName);
  if (!exists) {
    await minioClient.makeBucket(bucketName);
    // 创建桶后设置为公有读取策略
    await setBucketPublicReadPolicy();
  }
}

// 设置桶为公有读取策略
async function setBucketPublicReadPolicy() {
  const policy = {
    Version: '2012-10-17',
    Statement: [
      {
        Effect: 'Allow',
        Principal: { AWS: ['*'] },
        Action: ['s3:GetObject'],
        Resource: [`arn:aws:s3:::${bucketName}/*`]
      }
    ]
  };

  try {
    await minioClient.setBucketPolicy(bucketName, JSON.stringify(policy));
    console.log(`✅ 桶 ${bucketName} 已设置为公有读取策略`);
  } catch (error) {
    console.error(`❌ 设置桶策略失败:`, error);
    // 不抛出错误，避免影响文件上传功能
  }
}

function guessMimeType(filename: string): string {
  const ext = filename.split('.').pop()?.toLowerCase();
  switch (ext) {
    case 'png': return 'image/png';
    case 'jpg':
    case 'jpeg': return 'image/jpeg';
    case 'gif': return 'image/gif';
    case 'webp': return 'image/webp';
    case 'svg': return 'image/svg+xml';
    case 'pdf': return 'application/pdf';
    case 'txt': return 'text/plain';
    case 'json': return 'application/json';
    case 'zip': return 'application/zip';
    default: return 'application/octet-stream';
  }
}

export async function uploadFile(buffer: Buffer, objectKey: string, prefix = ''): Promise<{ url: string; path: string; mimeType: string; size: number }>{
  await ensureBucket();
  const key = `${prefix}${objectKey}`;
  const mimeType = guessMimeType(objectKey);
  await minioClient.putObject(bucketName, key, buffer, buffer.length, { 'Content-Type': mimeType });
  const fileBucketUrl = process.env.FILE_BUCKET_URL || 'https://www.kason.top';
  const minioEndpoint = process.env.MINIO_ENDPOINT || '175.178.120.172';
  const url = fileBucketUrl.startsWith('http') 
      ? `${fileBucketUrl}/${bucketName}/${key}`
      : `http://${minioEndpoint}:9000/${bucketName}/${key}`;
    
  return { url, path: key, mimeType, size: buffer.length };
}

// 导出设置公有桶策略的函数，供手动调用
export async function setBucketPublic(customBucketName?: string): Promise<boolean> {
  const targetBucket = customBucketName || bucketName;
  
  const policy = {
    Version: '2012-10-17',
    Statement: [
      {
        Effect: 'Allow',
        Principal: { AWS: ['*'] },
        Action: ['s3:GetObject'],
        Resource: [`arn:aws:s3:::${targetBucket}/*`]
      }
    ]
  };

  try {
    await minioClient.setBucketPolicy(targetBucket, JSON.stringify(policy));
    console.log(`✅ 桶 ${targetBucket} 已设置为公有读取策略`);
    return true;
  } catch (error) {
    console.error(`❌ 设置桶 ${targetBucket} 策略失败:`, error);
    return false;
  }
}

// 检查桶是否存在的导出函数
export async function checkBucketExists(customBucketName?: string): Promise<boolean> {
  const targetBucket = customBucketName || bucketName;
  try {
    return await minioClient.bucketExists(targetBucket);
  } catch (error) {
    console.error(`❌ 检查桶 ${targetBucket} 是否存在时出错:`, error);
    return false;
  }
}

// 手动创建桶的导出函数
export async function createBucket(customBucketName?: string, makePublic: boolean = true): Promise<boolean> {
  const targetBucket = customBucketName || bucketName;
  
  try {
    const exists = await minioClient.bucketExists(targetBucket);
    if (exists) {
      console.log(`ℹ️ 桶 ${targetBucket} 已存在`);
      if (makePublic) {
        return await setBucketPublic(targetBucket);
      }
      return true;
    }

    await minioClient.makeBucket(targetBucket);
    console.log(`✅ 桶 ${targetBucket} 创建成功`);
    
    if (makePublic) {
      return await setBucketPublic(targetBucket);
    }
    
    return true;
  } catch (error) {
    console.error(`❌ 创建桶 ${targetBucket} 失败:`, error);
    return false;
  }
}


